package com.mq.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 生产者
 */
@RestController
@RequestMapping("/producer")
@Slf4j
public class ProducerController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //简单队列  http://localhost:10010/producer/simpleQueue?message=hello
    @RequestMapping("/simpleQueue")
    public ResponseEntity simpleQueue(@RequestParam("message") String message) {
        log.info("生产者发送消息：{}", message);
        //将消息发送到队列中
        for (int i = 0; i < 10; i++) {
            rabbitTemplate.convertAndSend("simple.queue", message + i);
        }
        return ResponseEntity.ok("消息发送成功");
    }

    //广播模式 / 发布订阅模式
    // http://localhost:10010/producer/fanout?message=hello123
    @RequestMapping("/fanout")
    public ResponseEntity fanout(@RequestParam("message") String message) {
        log.info("生产者广播消息：{}", message);
        //将消息发送到交换机: 交换机 路由键(空) 消息
        rabbitTemplate.convertAndSend("X", null, message);
        return ResponseEntity.ok("消息发送成功");
    }



    //路由模式
    // http://localhost:10010/producer/direct?message=hello123
    @RequestMapping("/direct")
    public ResponseEntity direct(@RequestParam("message") String message) {
        rabbitTemplate.convertAndSend("direct.exchange", "sz", message);
        return ResponseEntity.ok("消息发送成功");
    }


    /**
     * 3. 绑定队列和交换机
     *      topic.queue1  topic.exchange  city.#
     *      topic.queue2  topic.exchange  gz.*
     * 主题模式
     *      http://localhost:10010/producer/topic?key=city.a.b
     *      http://localhost:10010/producer/topic?key=gz.a
     *      http://localhost:10010/producer/topic?key=gz.a.b
     */
    @RequestMapping("/topic")
    public ResponseEntity topic(@RequestParam("key") String key) {
        rabbitTemplate.convertAndSend("topic.exchange", key, "Hello!!!");
        return ResponseEntity.ok("消息发送成功");
    }
}